<template>
  <div class="my-applications-page">
    <!-- 头部 -->
    <div class="header-section">
      <div class="header-title">
        <el-icon class="title-icon"><Document /></el-icon>
        <h1>我的融资申请</h1>
      </div>
      <div class="header-actions">
        <el-button
          type="success"
          @click="loadMyApplications"
          :loading="applicationsLoading"
          class="refresh-btn"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 申请列表 -->
    <div class="applications-section">
      <el-card class="applications-card">
        <template #header>
          <div class="applications-header">
            <span class="applications-title">申请记录</span>
            <span class="applications-count">共 {{ myApplications.length }} 条申请记录</span>
          </div>
        </template>

        <el-table
          :data="myApplications"
          v-loading="applicationsLoading"
          style="width: 100%"
          empty-text="暂无融资申请记录"
        >
          <el-table-column label="产品名称" min-width="180">
            <template #default="{ row }">
              <div class="application-product">
                <span class="product-name">{{ row.productName }}</span>
                <el-tag
                  :type="getProductTypeTag(row.productType)"
                  size="small"
                  effect="plain"
                >
                  {{ getProductTypeText(row.productType) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="融资类型" width="120" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.financeType === 1 ? 'primary' : 'success'"
                effect="light"
              >
                {{ row.financeType === 1 ? '单独融资' : '联合融资' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="申请金额" width="140" align="center">
            <template #default="{ row }">
              <span class="amount">¥{{ row.applyAmount.toLocaleString() }}</span>
            </template>
          </el-table-column>

          <el-table-column label="申请时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatDate(row.applyTime) }}
            </template>
          </el-table-column>

          <el-table-column label="审核状态" width="120" align="center">
            <template #default="{ row }">
              <el-tag
                :type="getStatusType(row.status)"
                effect="light"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="联合融资状态" width="140" align="center" v-if="showJointFinanceColumn">
            <template #default="{ row }">
              <template v-if="row.financeType === 2">
                <el-tag
                  :type="row.jointStatus === 1 ? 'success' : row.jointStatus === 2 ? 'warning' : 'info'"
                  effect="light"
                >
                  {{ getJointStatusText(row.jointStatus) }}
                </el-tag>
              </template>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" align="center" fixed="right">
            <template #default="{ row }">
              <div class="application-actions">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="viewApplicationDetail(row)"
                >
                  <el-icon><View /></el-icon>
                  查看详情
                </el-button>
                <el-button
                  v-if="row.status === 0"
                  type="warning"
                  link
                  size="small"
                  @click="cancelApplication(row)"
                >
                  <el-icon><Close /></el-icon>
                  取消申请
                </el-button>
                <el-button
                  v-if="row.status === 2 && row.financeType === 2"
                  type="success"
                  link
                  size="small"
                  @click="confirmJointFinance(row)"
                >
                  <el-icon><Check /></el-icon>
                  确认参与
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <div v-if="myApplications.length === 0 && !applicationsLoading" class="empty-state">
          <el-empty description="暂无融资申请记录">
            <el-button type="primary" @click="$router.push('/farmer/financingServer/financingProducts')">
              去申请融资
            </el-button>
          </el-empty>
        </div>
      </el-card>
    </div>

    <!-- 申请详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="融资申请详情"
      width="700px"
      class="detail-dialog"
    >
      <div v-if="selectedApplication" class="application-detail">
        <!-- 基本信息 -->
        <el-descriptions title="申请信息" :column="2" border>
          <el-descriptions-item label="产品名称">
            {{ selectedApplication.productName }}
          </el-descriptions-item>
          <el-descriptions-item label="产品类型">
            <el-tag :type="getProductTypeTag(selectedApplication.productType)">
              {{ getProductTypeText(selectedApplication.productType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="融资类型">
            <el-tag :type="selectedApplication.financeType === 1 ? 'primary' : 'success'">
              {{ selectedApplication.financeType === 1 ? '单独融资' : '联合融资' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请金额">
            ¥{{ selectedApplication.applyAmount.toLocaleString() }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">
            {{ formatDate(selectedApplication.applyTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusType(selectedApplication.status)">
              {{ getStatusText(selectedApplication.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 贷款用途 -->
        <el-card class="detail-card" style="margin-top: 20px;">
          <template #header>
            <span class="detail-card-title">贷款用途</span>
          </template>
          <p>{{ selectedApplication.purpose }}</p>
        </el-card>

        <!-- 补充说明 -->
        <el-card class="detail-card" style="margin-top: 20px;" v-if="selectedApplication.remarks">
          <template #header>
            <span class="detail-card-title">补充说明</span>
          </template>
          <p>{{ selectedApplication.remarks }}</p>
        </el-card>

        <!-- 凭证文件 -->
        <el-card class="detail-card" style="margin-top: 20px;" v-if="selectedApplication.certificates && selectedApplication.certificates.length > 0">
          <template #header>
            <span class="detail-card-title">申请凭证</span>
          </template>
          <div class="certificates-list">
            <div
              v-for="(cert, index) in selectedApplication.certificates"
              :key="index"
              class="certificate-item"
            >
              <el-icon><Document /></el-icon>
              <span class="cert-name">{{ cert.name }}</span>
            </div>
          </div>
        </el-card>

        <!-- 审核意见 -->
        <el-card class="detail-card" style="margin-top: 20px;" v-if="selectedApplication.reviewComment">
          <template #header>
            <span class="detail-card-title">审核意见</span>
          </template>
          <p>{{ selectedApplication.reviewComment }}</p>
        </el-card>

        <!-- 联合融资信息 -->
        <el-card class="detail-card" style="margin-top: 20px;" v-if="selectedApplication.financeType === 2">
          <template #header>
            <span class="detail-card-title">联合融资信息</span>
          </template>
          <div class="joint-finance-info">
            <p>当前状态：{{ getJointStatusText(selectedApplication.jointStatus) }}</p>
            <p v-if="selectedApplication.jointPartners && selectedApplication.jointPartners.length > 0">
              已匹配伙伴：{{ selectedApplication.jointPartners.length }} 人
            </p>
            <el-button
              v-if="selectedApplication.jointStatus === 2"
              type="success"
              @click="confirmJointFinance(selectedApplication)"
            >
              确认参与联合融资
            </el-button>
          </div>
        </el-card>

        <!-- 操作按钮 -->
        <div class="detail-actions" style="margin-top: 24px; text-align: center;">
          <el-button
            v-if="selectedApplication.status === 0"
            type="warning"
            @click="cancelApplication(selectedApplication)"
          >
            取消申请
          </el-button>
          <el-button
            v-if="selectedApplication.status === 2 && selectedApplication.financeType === 2"
            type="success"
            @click="confirmJointFinance(selectedApplication)"
          >
            确认参与联合融资
          </el-button>
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document, Refresh, View, Close, Check
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const applicationsLoading = ref(false)
const showDetailDialog = ref(false)
const selectedApplication = ref(null)

// 我的融资申请数据
const myApplications = ref([])

// 计算属性
const showJointFinanceColumn = computed(() => {
  return myApplications.value.some(app => app.financeType === 2)
})

// 方法
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

const getProductTypeText = (type) => {
  const types = { 1: '信用贷', 2: '抵押贷', 3: '担保贷' }
  return types[type] || '未知类型'
}

const getProductTypeTag = (type) => {
  const tags = { 1: 'success', 2: 'warning', 3: 'primary' }
  return tags[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = { 0: '审核中', 1: '审核通过', 2: '审核拒绝', 3: '已取消' }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const types = { 0: 'warning', 1: 'success', 2: 'danger', 3: 'info' }
  return types[status] || 'info'
}

const getJointStatusText = (status) => {
  const statusMap = { 0: '未开始', 1: '匹配中', 2: '匹配完成', 3: '已确认', 4: '已取消' }
  return statusMap[status] || '未知状态'
}

const loadMyApplications = () => {
  applicationsLoading.value = true
  
  // 模拟加载延迟
  setTimeout(() => {
    // 从本地存储获取申请记录
    const storedApplications = JSON.parse(localStorage.getItem('financeApplications') || '[]')
    myApplications.value = storedApplications
    applicationsLoading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}

const viewApplicationDetail = (application) => {
  selectedApplication.value = application
  showDetailDialog.value = true
}

const cancelApplication = async (application) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消此融资申请吗？',
      '提示',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '再想想',
        type: 'warning'
      }
    )
    
    // 更新申请状态
    application.status = 3
    if (application.financeType === 2) {
      application.jointStatus = 4
    }
    
    // 更新本地存储
    updateLocalStorage()
    
    ElMessage.success('申请已取消')
    showDetailDialog.value = false
  } catch (error) {
    // 用户取消操作
  }
}

const confirmJointFinance = async (application) => {
  try {
    await ElMessageBox.confirm(
      '确认参与联合融资吗？确认后将进入放款流程。',
      '确认参与',
      {
        confirmButtonText: '确认参与',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    // 更新联合融资状态
    application.jointStatus = 3
    
    // 更新本地存储
    updateLocalStorage()
    
    ElMessage.success('已确认参与联合融资')
    showDetailDialog.value = false
  } catch (error) {
    // 用户取消操作
  }
}

const updateLocalStorage = () => {
  localStorage.setItem('financeApplications', JSON.stringify(myApplications.value))
}

// 初始化模拟数据（仅首次使用时）
const initializeMockData = () => {
  // 检查是否已有数据，如果没有则添加模拟数据
  const existingData = localStorage.getItem('financeApplications')
  if (!existingData || JSON.parse(existingData).length === 0) {
    const mockApplications = [
      {
        id: 1,
        productName: '农业生产经营贷款',
        productType: 1,
        financeType: 1,
        applyAmount: 50000,
        applyTime: '2024-01-15T10:30:00Z',
        status: 1,
        purpose: '用于购买春季种子和化肥',
        remarks: '土地承包合同已提供',
        certificates: [
          { name: '土地承包合同.pdf' },
          { name: '收入证明.docx' }
        ],
        reviewComment: '审核通过，符合贷款条件',
        jointStatus: null,
        jointPartners: []
      },
      {
        id: 2,
        productName: '农业设备抵押贷款',
        productType: 2,
        financeType: 2,
        applyAmount: 120000,
        applyTime: '2024-01-20T14:15:00Z',
        status: 2,
        purpose: '购买新型收割机设备',
        remarks: '设备清单和估价报告已附',
        certificates: [
          { name: '设备清单.xlsx' },
          { name: '设备估价报告.pdf' }
        ],
        reviewComment: '设备估值不足，建议降低贷款额度',
        jointStatus: 2,
        jointPartners: [
          { name: '王大明', amount: 30000 },
          { name: '李小红', amount: 25000 }
        ]
      },
      {
        id: 3,
        productName: '农产品加工贷款',
        productType: 3,
        financeType: 1,
        applyAmount: 80000,
        applyTime: '2024-02-01T09:45:00Z',
        status: 0,
        purpose: '建设农产品加工厂',
        remarks: '需要尽快审批，季节性强',
        certificates: [
          { name: '建厂规划图.pdf' },
          { name: '环保评估报告.docx' }
        ],
        reviewComment: null,
        jointStatus: null,
        jointPartners: []
      },
      {
        id: 4,
        productName: '特色农业种植贷款',
        productType: 1,
        financeType: 2,
        applyAmount: 30000,
        applyTime: '2024-02-05T16:20:00Z',
        status: 1,
        purpose: '发展有机蔬菜种植',
        remarks: '已与超市签订收购协议',
        certificates: [
          { name: '收购协议.pdf' },
          { name: '有机认证证书.pdf' }
        ],
        reviewComment: '项目前景良好，同意放款',
        jointStatus: 3,
        jointPartners: [
          { name: '张三', amount: 15000 },
          { name: '李四', amount: 10000 },
          { name: '王五', amount: 5000 }
        ]
      }
    ]
    localStorage.setItem('financeApplications', JSON.stringify(mockApplications))
  }
}

onMounted(() => {
  loadMyApplications()
  // 初始化模拟数据
  initializeMockData()
})
</script>

<style scoped>
.my-applications-page {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%);
  min-height: 100vh;
}

/* 头部样式 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
  padding: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  color: white;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title-icon {
  font-size: 36px;
}

.header-title h1 {
  margin: 0;
  font-size: 32px;
  font-weight: 700;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.refresh-btn {
  padding: 10px 24px;
  border-radius: 12px;
  font-weight: 600;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.refresh-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

/* 申请列表 */
.applications-section {
  margin-bottom: 32px;
}

.applications-card {
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.applications-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.applications-title {
  font-size: 20px;
  font-weight: 600;
  color: #2d3748;
}

.applications-count {
  color: #718096;
  font-size: 14px;
}

.application-product {
  display: flex;
  align-items: center;
  gap: 8px;
}

.product-name {
  font-weight: 500;
}

.amount {
  font-weight: 600;
  color: #e53e3e;
}

.text-muted {
  color: #a0aec0;
}

.application-actions {
  display: flex;
  justify-content: center;
  gap: 8px;
}

/* 空状态 */
.empty-state {
  padding: 60px 0;
}

/* 详情样式 */
.detail-dialog {
  border-radius: 16px;
}

.application-detail {
  padding: 8px 0;
}

.detail-card {
  border-radius: 8px;
}

.detail-card-title {
  font-weight: 600;
  color: #2d3748;
}

.certificates-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.certificate-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.cert-name {
  color: #4a5568;
  font-size: 14px;
}

.joint-finance-info {
  color: #4a5568;
  line-height: 1.6;
}

.detail-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-applications-page {
    padding: 16px;
  }
  
  .header-section {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
    padding: 24px;
  }
  
  .header-title {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .header-title h1 {
    font-size: 24px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .applications-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  .application-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .detail-actions {
    flex-direction: column;
    gap: 8px;
  }
}
</style>